package encodeutil

import (
    "encoding/base64"
    "github.com/tjfoc/gmsm/sm4"
    "gmap-backend/internal/util/commonutil"
    "strings"
)

// EncryptSm4 使用sm4加密文本，文本会先进行trim处理
func EncryptSm4(str string, key string) string {
    str = strings.TrimSpace(str)
    if "" == str {
        return ""
    }
    validateSm4Key(&key)
    keyBytes := []byte(key)
    dataBytes := []byte(str)
    encodedBytes, err := sm4.Sm4Ecb(keyBytes, dataBytes, true)
    commonutil.ThrowIfNeed(err)
    if 0 == len(encodedBytes) {
        panic("sm4加密失败")
    }
    encodedBase64Txt := base64.StdEncoding.EncodeToString(encodedBytes)
    return encodedBase64Txt
}

// DecryptSm4 使用sm4解密文本，文本会先进行trim处理
func DecryptSm4(str string, key string) string {
    str = strings.TrimSpace(str)
    if "" == str {
        return ""
    }
    validateSm4Key(&key)
    keyBytes := []byte(key)
    dataBytes, err := base64.StdEncoding.DecodeString(str)
    commonutil.ThrowIfNeed(err)
    decodedBytes, err2 := sm4.Sm4Ecb(keyBytes, dataBytes, false)
    commonutil.ThrowIfNeed(err2)
    if 0 == len(decodedBytes) {
        panic("sm4解密失败")
    }
    return string(decodedBytes)
}

// validateSm4Key 验证sm4 key的格式，不允许为空，只允许16字节
func validateSm4Key(key *string) {
    if key == nil {
        panic("请指定sm4密钥")
    }
    if 16 != len(*key) {
        panic("sm4密钥必须为128位，即16字节")
    }
}
